export const loadNDJSON = async (
  url,
  renderCallback = () => {},
  sid = null,
  querys = {},
  header = {}
) => {
  const items = []
  let buffer = ''
  let previousLine

  const userId = '1'

  querys.list[0].userId = userId

  try {
    let pathURL = url
    const formData = new FormData()

    querys.list.forEach((item) => {
      formData.append('sessionId', item.session_id)
      formData.append('business', '超套')
      formData.append('userId', userId)
      formData.append('phone', item.phone)
      formData.append('tag', item.tag ? item.tag : 'entry')
    })

    const files = querys.list[0].fileList || []
    let response

    const apiUrl = import.meta.env.VITE_APP_BASE_APIURL

    response = await fetch(apiUrl + pathURL, {
      method: 'post',
      headers: {
        ...header
      },
      body: formData
    })

    if (!response.ok) {
      renderCallback(
        {
          data: {
            content: 'error',
            isMarkdown: false
          }
        },
        sid
      )
      return items
    }

    const reader = response.body?.getReader()

    const decoder = new TextDecoder()
    let done = false

    while (!done) {
      const { value, done: readerDone } = await reader.read()
      done = readerDone
      // console.log("value", value);

      if (value) {
        // 将新数据添加到缓冲区
        buffer += decoder.decode(value, { stream: true })
        // console.log(buffer, 1111111111111111111)
        // console.log("buffer", buffer);

        // 按行分割
        const lines = buffer.split('\n')

        // 保留最后一行（可能不完整）
        buffer = lines.pop() || ''
        // buffer = lines;

        // console.log('lines', lines)

        // 如果有不完整的行，打印上下文
        if (buffer) {
          console.group('Incomplete line with context:')
          if (previousLine) {
            console.log('Previous complete line:', previousLine)
          }
          console.log('Current incomplete line:', buffer)
          if (lines.length > 0) {
            console.log('Next complete line:', lines[lines.length - 1])
          }
          console.groupEnd()
        }

        // 处理完整的行
        for (const line of lines) {
          // console.log("line", line);
          if (line.trim()) {
            // 跳过空行
            try {
              // console.log("line========>", line.content);
              // console.log(
              //   "JSON.parse(line)========>",
              //   JSON.parse(line).data.content
              // );
              const Data = JSON.parse(line)
              // console.log("Data========>", Data);
              const parsedData = JSON.parse(JSON.stringify(Data))
              // console.log("parsedData========>", parsedData);

              items.push(parsedData)
              // console.log("parsedData,", parsedData);
              renderCallback(parsedData, sid)
              previousLine = line // 更新上一行
            } catch (e) {
              console.log(e)
              console.error('Error parsing line:', line, e)
            }
          }
        }
      }
    }
  } catch (error) {
    console.error('Error loading NDJSON data:', error)
    throw error
  }

  return items
}
